package com.server.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.server.model.OsaUserInfo;
import com.server.service.IOsaUserInfoService;
import com.server.utils.BaseResult;
import com.server.utils.MD5Utils;
import com.server.utils.UUIDUtil;
import com.server.utils.UserSessionMapUtils;
import com.server.utils.WXAppUserInfo;

/**
 * 微信登录小程序
 * @author Andrew
 *
 */
@RestController
@RequestMapping(value = "/login")
public class WXAppLoginController {

	private static Logger logger = Logger.getLogger(WXAppLoginController.class);
	
	@Autowired
	private IOsaUserInfoService iOsaUserInfoService;
	
	@RequestMapping(value = "/check")
	public JSONObject login(@RequestParam String jsCode, @RequestParam String encryptedData, @RequestParam String iv) {
		BaseResult result = new BaseResult();
		JSONObject json = new JSONObject();
		OsaUserInfo user = null;
		// 获取用户微信openID相关信息
		JSONObject data = WXAppUserInfo.getSessionKeyOrOpenId(jsCode);
		String openId = data.getString("openid");
		String sessionKey = data.getString("session_key");
		logger.info(data);
		JSONObject userJson = WXAppUserInfo.getUserInfo(encryptedData, sessionKey, iv);
		logger.info(userJson);
		// 生成sessionCode
		String sessionCode = MD5Utils.getMD5(openId + sessionKey);
		json.put("sessionCode", sessionCode);
		// 查询用户是否已经存在
		OsaUserInfo param = new OsaUserInfo();
		param.setOpenId(openId);
		List<OsaUserInfo> users = iOsaUserInfoService.find(param);
		if (users != null && users.size() > 0) {
			user = users.get(0);
			// 判断用户信息是否完整
			if (user.getRealName() == null || user.getPhoneNum() == null || user.getQq() == null) {
				result.setCode("101");
				result.setMsg("请补充用户信息");
			} else {
				result.setCode("100");
				result.setMsg("成功");
			}
		} else {
			String headImg = userJson.getString("avatarUrl");
			String sex = userJson.getString("gender");
			String nickName = userJson.getString("nickName");
			// 生成用户记录，返回让用户补充信息
			user = new OsaUserInfo();
			user.setOpenId(openId);
			user.setUserCode(UUIDUtil.getUuid());
			user.setHeadImg(headImg);
			user.setNickName(nickName);
			user.setSex(Integer.parseInt(sex));
			Long userId = iOsaUserInfoService.insert(user);
			user.setUserId(userId);
			result.setCode("101");
			result.setMsg("请补充用户信息");
		}
		UserSessionMapUtils.deleteUserInfo(openId);
		UserSessionMapUtils.putUser(sessionCode, user);
		result.setData(json);
		return JSONObject.parseObject(JSON.toJSON(result).toString());
	}
}
